package com.CmJava.servlet.handlerAdapter;

import com.CmJava.annotation.RequestMapping;
import com.CmJava.annotation.ResponseBody;
import com.CmJava.servlet.DispatcherServlet;
import com.CmJava.servlet.executionChain.handlerMethodMapping.HandlerMethod;
import com.CmJava.servlet.modelAndView.ModelAndViewContainer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HandlerMethodReturnValueHandlerComposite {

    public void handleReturnValue(Object returnValue, ModelAndViewContainer mavContainer, HttpServletRequest request, HttpServletResponse response) {
        if (returnValue instanceof CharSequence) {
            String viewName = returnValue.toString();
            HandlerMethod handlerMethod = DispatcherServlet.abstractHandlerMethodMapping.getMappingRegistry().getMappings().get(request.getRequestURI());
            //这里就没写那么深了，@RequestMapping的请求直接在这里传回去了
            if (handlerMethod.getMethod().isAnnotationPresent(ResponseBody.class)) {
                response.addHeader("Content-Type","text/html;charset=UTF-8");
                ServletOutputStream outputStream=null;
                try {
                    outputStream = response.getOutputStream();
                    outputStream.write(viewName.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (outputStream!=null){
                        try {
                            outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else {
                mavContainer.setViewName(viewName);
            }
        }
    }
}
